import React, { useEffect, useState } from 'react';
import moment from 'moment'
import {
  Table, Modal, Form, Input, Col, message, InputNumber, Select, Button, TimePicker,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  handleSupplier,
} from '@/services/goodCenter/invoicing';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
// const {  } = DatePicker

const statusLists = ['', '空闲/正常', '已预定', '使用中', '维修中']
const arrtion = ['否', '是']
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '台房名称',
    align: 'center',
    key: 'name',
  },
  {
    title: '楼层',
    align: 'center',
    key: 'floorName',
  },
  {
    title: '类型',
    align: 'center',
    key: 'typeName',
  },
  {
    title: '保底消费',
    align: 'center',
    key: 'limitAmount',
  },
  {
    title: '状态',
    align: 'center',
    key: 'status',
    render: p => (<span>{ statusLists[p.status] }</span>),
  },
  {
    title: '是否开启预定',
    align: 'center',
    key: 'isReservation',
    render: p => (<span>{ arrtion[p.isReservation] }</span>),
  },
  {
    title: '是否开启排班',
    align: 'center',
    key: 'isScheduling',
    render: p => (<span>{ arrtion[p.isScheduling] }</span>),
  },
  {
    title: '创建时间',
    align: 'center',
    key: 'createTime',
  },
];
const statusList = [
  {
    label: '空闲/正常',
    value: '1',
  },
  {
    label: '已预定',
    value: '2',
  },
  {
    label: '使用中',
    value: '3',
  },
  {
    label: '维修中',
    value: '4',
  },
]
const distrotionRoom = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [floors, setfloors] = useState([]);
  const [roomtypes, setroomtypes] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [endTime, setendTime] = useState(null);
  const [startTime, setstartTime] = useState(null);
  const [checkhour, setcheckhour] = useState([]);
  const [checkmin, setcheckmin] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);
  const [confirmLoading, setconfirmLoading] = useState(false);

  // 列表
  const getList = async params => {
    const r = await handleSupplier(params, 'GET');
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, [listQuery]);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  const removeRole = async record => {
    handleSupplier({
      id: record.id,
    }, 'DELETE').then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="台房名称">
          <Input onChange={v => { setListQuery({ ...listQuery, name: v.target.value }) }} placeholder="市别名称" value={listQuery.name} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="楼层名称">
          <Select value={listQuery.floorId} placeholder="选择楼层名称" onChange={v => { setListQuery({ ...listQuery, floorId: v }) }}>
            {floors.map(r => <Option key={r.id}>{r.label}</Option>)}
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="台房类型">
          <Select value={listQuery.typeId} placeholder="选择台房类型" onChange={v => { setListQuery({ ...listQuery, typeId: v }) }}>
            {roomtypes.map(r => <Option key={r.id}>{r.label}</Option>)}
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select value={listQuery.status} placeholder="选择状态" onChange={v => { setListQuery({ ...listQuery, status: v }) }}>
            {statusList.map(r => <Option key={r.value}>{r.label}</Option>)}
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      console.log(values)
      console.log(values.startTime.format('HH:mm'))
      if (!err) {
        // let med = 'POST'
        // if (values.id) {
        //   med = 'PUT'
        // }
        // setconfirmLoading(true)
        // handleSupplier({ storeBusiness: values }, med).then(() => {
        //   getList(listQuery)
        //   setState(!isShow);
        //   setconfirmLoading(false)
        // }).catch(() => {
        //   setconfirmLoading(false)
        // })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      // 删除
      case 4:
        return removeRole(record[0]);
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  const timepchange = (tm, ts) => {
    const aarr = ts.split(':')
    setcheckhour(parseInt(aarr[0]))
    setcheckmin(parseInt(aarr[1]))
    if (info.endTime) {
      setInfo({ ...info, endTime: null })
      props.form.setFieldsValue({ endTime: null })
    }
  }
  const disableHour = () => {
    console.log('disable')
    let hour = checkhour
    const hourarrs = []
    while (hour >= 0) {
      hour--
      if (hour >= 0) {
        hourarrs.push(hour)
      }
    }
    return hourarrs
  }
  const disableMin = h => {
    console.log(`min ${h}`)
    if (h <= checkhour || h === null) {
      let min = checkmin
      const minarrs = []
      while (min >= 0) {
        min--
        if (min >= 0) {
          minarrs.push(min)
        }
      }
      return minarrs
    }
    return []
  }
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        confirmLoading={confirmLoading}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="市别名称">
            {getFieldDecorator('name', {
              initialValue: info.name,
              rules: [
                {
                  required: true,
                  message: '请输入市别名称',
                },
              ],
            })(<Input placeholder="请输入市别名称" />)}
          </Form.Item>
          <Form.Item label="台房类型">
            {getFieldDecorator('typeId', {
              initialValue: info.typeId,
              rules: [
                {
                  required: true,
                  message: '请选择台房类型',
                },
              ],
            })(<Select placeholder="选择台房类型">
              {roomtypes.map(r => <Option key={r.id}>{r.name}</Option>)}
            </Select>)}
          </Form.Item>
          <Form.Item label="普通价格">
            {getFieldDecorator('normalPrice', {
              initialValue: info.normalPrice,
              rules: [
                {
                  required: true,
                  message: '请输入普通价格',
                },
              ],
            })(<InputNumber className="width100" min={0} placeholder="请输入普通价格" />)}
          </Form.Item>
          <Form.Item label="活动价">
            {getFieldDecorator('activityPrice', {
              initialValue: info.activityPrice,
              rules: [
                {
                  required: true,
                  message: '请输入活动价',
                },
              ],
            })(<InputNumber className="width100" min={0} placeholder="请输入活动价" />)}
          </Form.Item>
          <Form.Item label="会员价">
            {getFieldDecorator('memberPrice', {
              initialValue: info.memberPrice,
              rules: [
                {
                  required: true,
                  message: '请输入会员价',
                },
              ],
            })(<InputNumber className="width100" min={0} placeholder="请输入会员价" />)}
          </Form.Item>
          <Form.Item label="开启时间">
            {getFieldDecorator('startTime', {
              initialValue: info.startTime ? moment(info.startTime) : null,
              rules: [
                {
                  required: true,
                  message: '请选择开启时间',
                },
              ],
            })(<TimePicker format="HH:mm" placeholder="开启时间" onChange={timepchange} />)}
          </Form.Item>
          <Form.Item label="结束时间">
            {getFieldDecorator('endTime', {
              initialValue: info.endTime ? moment(info.endTime) : null,
              rules: [
                {
                  required: true,
                  message: '请选择结束时间',
                },
              ],
            })(<TimePicker format="HH:mm" hideDisabledOptions disabledHours={disableHour.bind(this)} disabledMinutes={disableMin.bind(this)} placeholder="结束时间" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(distrotionRoom));
